//
//  WKWebViewController.swift
//  DemoProject
//
//  Created by Hao on 2018/8/23.
//  Copyright © 2018年 hao. All rights reserved.
//

import UIKit
import WebKit

class WKWebViewController: BaseViewController {

    /** 是否隐藏底部工具view */
    var isHiddenBottomToolView = false {
        didSet {
            if let toolView = self.bottomToolView {
                toolView.isHidden = isHiddenBottomToolView
            } else {
                if !isHiddenBottomToolView {
                    self.setupView()
                }
            }
        }
    }
    
    var loadUrl : String? {
        didSet {
            guard let strUrl = loadUrl else { return }
            if strUrl.hasPrefix("http") {
                guard let url = URL(string: strUrl) else { return }
                webView.load(URLRequest(url: url))
            } else {
                webView.loadHTMLString(strUrl, baseURL: nil)
            }
            self.view.addSubview(webView)
        }
    }
    
    fileprivate var bottomToolView: UIView?
    fileprivate lazy var webView : WKWebView = {
        var y = CGFloat(0)
        var height = MainScreenHeight()
        if self.navigationController?.navigationBar != nil {
            y = kStatusBarAndNaviHeight()
            height -= y
        } else {
            y = kStatusBarHeight()
        }
//        if let tabBar = self.tabBarController?.tabBar {
//            /** 如果tabbar没有隐藏 */
//            if !tabBar.isHidden {
//                height -= kTabBarHeight()
//            }
//        }
        let webV = WKWebView(frame: CGRect(x: 0, y: y, width: MainScreenWidth(), height: height))
        // 如果 底部view 是隐藏的
        if self.isHiddenBottomToolView {
            webV.frame.size.height = MainScreenHeight()
        }
        webV.navigationDelegate = self
        webV.allowsBackForwardNavigationGestures = true
        return webV
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if !self.isHiddenBottomToolView {
            self.setupView()
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        if let tabBar = self.tabBarController?.tabBar {
            /** 如果tabbar没有隐藏 */
            if !tabBar.isHidden {
                self.webView.height -= kTabBarHeight()
            }
        }
        super.viewDidAppear(animated)
    }
    
}

extension WKWebViewController {
    
    fileprivate func setupView() {
        if self.bottomToolView != nil { return }
        let toolViewHeight = kTabBarHeight()
        let bottomToolView = UIView(frame: CGRect(x: 0, y: self.webView.frame.maxY-toolViewHeight, width: MainScreenWidth(), height: toolViewHeight))
        bottomToolView.backgroundColor = UIColor.white
        self.view.addSubview(bottomToolView)
        let images = ["webview_tool_back",
                      "webview_tool_next",
                      "webview_tool_zhuanfa",
                      "webview_tool_first",
                      "webview_tool_refresh"]
        // 创建五个按钮
        for i in 0 ..< images.count {
            let btn = UIButton(type: UIButtonType.system)
            guard let image = UIImage(named: images[i]) else { return }
            btn.setImage(image, for: UIControlState.normal)
            let width = MainScreenWidth()/CGFloat(images.count);
            let btnX = CGFloat(i)*width
            btn.frame = CGRect(x: btnX, y: 0, width: width, height: toolViewHeight)
            bottomToolView.addSubview(btn)
            btn.tag = i+10
            btn.addTarget(self, action: #selector(toolBtnClick(btn:)), for: UIControlEvents.touchUpInside)
        }
        
        let topLineView = UIView()
        topLineView.backgroundColor = kColorWithRGB(190, 190, 190)
        bottomToolView.addSubview(topLineView)
        topLineView.frame = CGRect(x: 0, y: 0, width: MainScreenWidth(), height: 0.5)
        self.bottomToolView = bottomToolView
    }
    
    @objc fileprivate func toolBtnClick(btn: UIButton) {
        switch btn.tag {
        case 10: // 上一个界面
            if self.webView.canGoBack {
                self.webView.goBack()
            } else {
                self.navigationController?.popViewController(animated: true)
            }
        case 11: // 下一个界面
            self.webView.goForward()
        case 12: // 转发
            print(info: "转发")
        case 13: // 回到第一个界面
            guard let strUrl = self.loadUrl else { return }
            guard let url = URL(string: strUrl) else { return }
            self.webView.load(URLRequest(url: url))
        case 14: // 刷新
            self.webView.reload()
        default:
            break
        }
    }
    
}

extension WKWebViewController : WKNavigationDelegate {
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        
    }

}

// MARK: 测试WKWebViewController
class TestWKWebViewController: WKWebViewController {
    var dataArr = [[String : AnyObject]]()
    
    lazy var indicatorView: UIActivityIndicatorView = {
        let _indicatorView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
        view.addSubview(_indicatorView)
        _indicatorView.snp.makeConstraints({ (make) in
            make.center.equalTo(self.view)
        })
        _indicatorView.hidesWhenStopped = true
        return _indicatorView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.indicatorView.startAnimating()
        self.loadUrl = "https://www.baidu.com/"
//        self.loadUrl = "https://h5.m.taobao.com/app/movie/pages/index/index.html"
//        self.loadUrl = "http://suo.im/VeoP6"
        
//        let path = "/Users/hao/Desktop/iOS/TestWebView/baidu.txt"
//        let path = "/Users/hao/Desktop/iOS/TestWebView/taopiao1.txt"
//        self.loadUrl = try String(contentsOfFile: path, encoding: String.Encoding.utf8)

//        Alamofire.request("https://h5.m.taobao.com/app/movie/pages/index/index.html").responseData { (response) in
//            if let value = response.result.value {
//                if let result = String(data: value, encoding: String.Encoding.utf8) {
//                    print("result = \(result)")
//                }
//            }
//        }
    }
    
}

fileprivate var count = 0
extension TestWKWebViewController {
    
    override func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        self.indicatorView.stopAnimating()
        print(info: "加载完毕")
//        return
        DispatchQueue.main.asyncAfter(deadline: DispatchTime(uptimeNanoseconds: 3), execute: {
            let js = "document.documentElement.outerHTML"
            webView.evaluateJavaScript(js) { (html, error) in
                if let html = html as? NSString {
                    print(info: "html body = \(html)")
                    do {
                        try
                            html.write(toFile: "/Users/hao/Desktop/iOS/TestWebView/biaoti1.txt", atomically: true, encoding: String.Encoding.utf8.rawValue)
                    } catch {
                        print(info: error)
                    }
                }
            }
        })
    }
    
    /** 在收到响应后，决定是否跳转的代理 */
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        //        let response = navigationResponse.response
        //        print("response = \(response)")
        count += 1
        decisionHandler(.allow)
    }
    
    /** 接收到服务器跳转请求的代理 */
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        var dict = [String : AnyObject]()
        let request = navigationAction.request
//        if let cookies = HTTPCookieStorage.shared.cookies {
//            dict.updateValue(cookies as AnyObject, forKey: "cookies")
//            for cookie in cookies {
//                if let properties = cookie.properties {
//                    print("properties = \(properties)")
//                }
//                print("version = \(cookie.version)")
//                print("name = \(cookie.name), value = \(cookie.value)")
//            }
//        }
        if let headers = request.allHTTPHeaderFields {
            dict.updateValue(headers as AnyObject, forKey: "header")
            print(info: headers)
        }
        if let urlStr = navigationAction.request.url?.absoluteString {
            print(info: "url = \(urlStr)")
            // 如果 url 有该前缀就拦截
            if urlStr.hasPrefix("gotourl") {
                decisionHandler(.cancel)
                return
            }
        }
        
//        (dict as NSDictionary).write(toFile: "/Users/hao/Desktop/iOS/TestWebView/\(count).plist", atomically: true)
        decisionHandler(.allow)
    }
    
}



